package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.byit.builder.MapBuilder;
import com.byit.domain.AppCategory;
import com.byit.msg.MessageResult;
import com.byit.service.IAppApplictionMenuService;
import com.byit.service.IAppCategoryService;
import com.byit.service.IAppUserApplictionService;
import com.byit.utils.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/4.
 * 应用分类
 */

@RestController
@RequestMapping("/app/category")
public class AppCategoryController {


    @Autowired
    private IAppCategoryService categoryService;
    @Autowired
    private IAppApplictionMenuService applictionMenuService;
    @Autowired
    private IAppUserApplictionService appUserApplictionService;

    /**
     * 所有分类列表
     *
     * @return
     */
    @GetMapping("/all")
    public Object all(HttpServletRequest request) {
        String ipAddr = IpUtils.getRequestURL(request);
        List<AppCategory> categories = categoryService.selectAll();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (AppCategory category : categories) {
            List<JSONObject> menus = applictionMenuService.selectAllApplication(MapBuilder.newMap(1)
                    .setParam("categoryId", category.getId()).ok());
            if (null != menus && menus.size() > 0) {
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("id", category.getId());
                data.put("name", category.getName());
                for (JSONObject obj : menus) {
                    String url = obj.getString("url");
                    if (null == url || (url.indexOf("https://") < 0 && url.indexOf("http://") < 0 && url.indexOf("app") < 0)) {
                        obj.put("url", ipAddr + "/app/h5/noData.html");
                    }
                }
                data.put("memus", menus);
                list.add(data);
            }

        }

        return MessageResult.success(list);
    }


}
